<template>
  <el-config-provider :locale="locale">
    <RouterView />
  </el-config-provider>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
import { uuid } from './utils'

const language = ref('zh-cn')
const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en))

let websocket = null
let token = null

const onOpen = () => {
  console.log('WebSocket连接成功，状态码：', websocket.readyState)
}
const onMessage = (event) => {
  ElNotification({
    title: '收到消息',
    message: h('span', { style: 'color: teal' }, event.data)
  })
}
const onError = () => {
  console.log('WebSocket连接错误，状态码：', websocket.readyState)
}
const onClose = () => {
  console.log('WebSocket连接关闭，状态码：', websocket.readyState)
}
const initWebSocket = () => {
  // 连接成功回调
  websocket.onopen = onOpen
  // 收到消息回调
  websocket.onmessage = onMessage
  // 连接错误回调
  websocket.onerror = onError
  // 连接关闭回调
  websocket.onclose = onClose
}

onMounted(() => {
  if ('WebSocket' in window) {
    token = uuid(10)
    websocket = new WebSocket(import.meta.env.VITE_WS_URL + 'ws/' + token)
    initWebSocket()
  } else {
    console.error('当前浏览器不支持 WebSocket')
  }
})
</script>

<style scoped></style>
